<template>
<div class="app-container">
  <div style="width: 920px">
    <el-form ref="form" :rules="rules" :model="form" label-width="120px">
      <el-form-item label="专栏名称" prop="name">
        <el-input size="small" v-model="form.name" placeholder="请输入专栏名称" />
      </el-form-item>
      <el-form-item label="专栏分类" prop="classify">
        <div>
          当前所属分类：{{fullName}}
        </div>
        <el-cascader style="width:100%;" @change="changeType" @expand-change="expandChangeType" v-model="form.classify" :options="options" size="small" :props="props"></el-cascader>
      </el-form-item>
      <el-form-item label="专栏描述" prop="des">
        <!-- <el-input type="textarea" :rows="5" size="small" v-model="form.des" placeholder="请输入专栏描述" /> -->
        <tinymce v-model="form.des" :height="300" placeholder="请输入专栏描述"/>
      </el-form-item>
      <el-form-item label="专栏海报" required>
        <div style="color:#999">
          建议尺寸714*344px或2：1，JPG、PNG格式， 图片小于5M。
        </div>
        <el-upload
          :class="imgFilesList.length?'hiddenUpload':''"
          action="https://service.bairicun.com/file/upload"
          list-type="picture-card"
          :on-success="handleSuccess"
          :file-list="imgFilesList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="报名时间" prop="baoTime">
        <el-date-picker
          style="width:100%;"
          size="small"
          v-model="form.baoTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          align="right">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="选择试卷">
        <div style="display:flex;align-items:center;">
          <div style="margin-right:10px;">
            <span>
              练习试卷
            </span>
            <el-select clearable size="small" v-model="form.testId" placeholder="请选择练习试卷">
              <el-option
                v-for="(item,index) in testList"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
          <div style="margin-right:10px;">
            <span>
              作业试卷
            </span>
            <el-select clearable size="small" v-model="form.taskId" placeholder="请选择作业试卷">
              <el-option
                v-for="(item,index) in taskList"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
          <div style="margin-right:10px;">
            <span>
              考试试卷
            </span>
            <el-select clearable size="small" v-model="form.examId" placeholder="请选择考试试卷">
              <el-option
                v-for="(item,index) in examList"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="选择课程">
        <div style="display:flex;">
          <div>
            已选择：
          </div>
          <div>
            <div style="display:flex;align-items:center;" v-for="(item,index) in choosedCourseList" :key="index">
              <div style="width:100px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;" :title="item.name">
                {{item.name}}
              </div>
              <div>
                <el-input v-model="item.sort" type="number" size="small" placeholder="请输入排序" />
              </div>
            </div>
          </div>
        </div>
        <el-button @click="openCourse" size="small" type="primary">选择课程</el-button>
      </el-form-item>
      <el-form-item label="专栏费用" prop="fee">
        <el-input type="number" size="small" v-model="form.fee" placeholder="请输入费用" />
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" @click="onSubmit('form')">保存</el-button>
        <el-button size="small" @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>

    <el-dialog top="10vh" width="1000px" title="选择专栏课程" :visible.sync="modalVisible">
      <div style="display:flex;align-items: center;justify-content: space-between;margin:0 0 10px;">
        <div style="display:flex;align-items: center;">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="课程名称">
              <el-input clearable size="small" v-model="pageObj.name" placeholder="标题"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button size="small" type="primary" @click="onSubmit">搜索</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <el-table row-key="id" style="width: 100%" @select="handleSelectionChange" ref="multipleTable" v-loading="listLoading" :data="tableList" element-loading-text="Loading" border fit highlight-current-row empty-text="暂无数据">
        <el-table-column

          type="selection"
          reserve-selection
          width="80">
        </el-table-column>
        <el-table-column label="ID" width="150">
          <template slot-scope="scope">
            {{ scope.row.id }}
          </template>
        </el-table-column>
        <el-table-column label="课程名称">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="主讲教师" width="200">
          <template slot-scope="scope">
            {{ scope.row.teacherList&&scope.row.teacherList.length&&scope.row.teacherList[0].realName }}
          </template>
        </el-table-column>
      </el-table>

      <div style="margin:10px 0 0 0;text-align:right;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageObj.pageNum"
          :page-sizes="[10, 30, 50, 100]"
          :page-size="pageObj.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageObj.total">
        </el-pagination>
      </div>

      <div slot="footer" class="dialog-footer" style="text-align:center;">
        <el-button size="small" type="primary" @click="modalVisible = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import {
  gettypeListApi,
  getTypeListById,
  saveApi,
  getDetailApi
} from '@/api/column'

import {
  getListApi,
} from '@/api/course'

import {
  getListPaperApi
} from '@/api/paper'

export default {
  components: {Tinymce},
  data() {
    let _this = this
    return {
      typeId: [],
      props: {
        value: 'id',
        label: 'name',
        lazy: true,
        async lazyLoad (node, resolve) {
          if (node.data) {
            setTimeout(() => {
              _this.getChildArea(node, resolve)//懒加载后几层数据
            }, 1000);
          }
        }
      },
      options: [],
      searchTypeId: '',
      selectTypeId: '',
      radio: '',
      tableList: [],
      listLoading: true,
      formInline: {
        title: ''
      },
      form: {
        id: '',
        name: '',
        des: '',
        fee: null,
        classify: [],
        testId: '',
        taskId: '',
        examId: '',
        baoTime: [],
      },
      rules: {
        name: [{
          required: true,
          message: '请输入标题',
          trigger: 'blur'
        }, ],
        des: [{
          required: true,
          message: '请输入描述',
          trigger: 'blur'
        }, ],
        classify: [{
          required: false,
          message: '请选择专栏分类',
          trigger: 'change'
        }, ],
        fee: [{
          required: false,
          message: '请输入费用',
          trigger: 'blur'
        }, ],
      },
      dialogImageUrl: '',
      dialogVisible: false,
      uploadStatus: false,
      uploadUrl: '',
      uploadImgId: '',
      modalVisible: false,
      choosedCourseList: [],
      choosedCourseNewList: [],
      pageObj: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        name: '',
      },
      detailObj: {},
      imgFilesList: [],
      fullName: '',
      testList: [],
      taskList: [],
      examList: [],
    }
  },
  mounted() {
    this.getDetail()
    this.getTypeList()
    this.getTestList()
    this.getTaskList()
    this.getExamList()
  },
  methods: {
    getTestList() {
      getListPaperApi({
        pageSize: 1000,
        pageNum: 1,
        type: 1,
      }).then((res) => {
        this.testList = res.data.result.map((item) => {
          return {
            value: item.id,
            label: item.paperName
          }
        })
      })
    },
    getTaskList() {
      getListPaperApi({
        pageSize: 1000,
        pageNum: 1,
        type: 0,
      }).then((res) => {
        this.taskList = res.data.result.map((item) => {
          return {
            value: item.id,
            label: item.paperName
          }
        })
      })
    },
    getExamList() {
      getListPaperApi({
        pageSize: 1000,
        pageNum: 1,
        type: 2,
      }).then((res) => {
        this.examList = res.data.result.map((item) => {
          return {
            value: item.id,
            label: item.paperName
          }
        })
      })
    },
    getDetail() {
      getDetailApi(this.$route.query.editId).then((res) => {
        this.detailObj = res.data
        this.form.name = res.data.name
        this.form.des = res.data.des
        this.form.id = res.data.id
        this.form.fee = res.data.fee
        this.selectTypeId = res.data.courseTypeId
        this.form.testId = res.data.exercisePaperId
        this.form.taskId = res.data.workPaperId
        this.form.examId = res.data.examPaperId
        this.fullName = res.data.courseTypeDetail.fullName
        this.form.baoTime = [res.data.enrollStartTime, res.data.enrollEndTime]

        console.log(this.form.classify)
        this.choosedCourseList = res.data.lessonVOList
        this.imgFilesList = [
          {
            url: res.data.picUrl,
            id: res.data.picId,
          }
        ]
        this.uploadImgId = res.data.picId
      })
    },
    handleSelectionChange(e,row) {
      let chooseIds = this.choosedCourseList.map((item) => {return item.id})
      if(chooseIds.indexOf(String(row.id)) > -1) {
        this.choosedCourseList = this.choosedCourseList.filter((item) => {
          return item.id != row.id
        })
      } else {
        this.choosedCourseList.push(row)
      }
    },
    getCourseList() {
      this.listLoading = true
      getListApi({
        pageSize: this.pageObj.pageSize,
        pageNum: this.pageObj.pageNum,
        name: this.pageObj.name
      }).then((res) => {
        this.listLoading = false
        this.tableList = res.data.result
        this.pageObj.total = res.data.total
        let that=this
        this.$nextTick(() => {
          // this.$refs["multipleTable"].clearSelection();
          for(let i=0;i<that.tableList.length;i++){
            for(let j=0;j<that.choosedCourseList.length;j++){
              if(that.tableList[i].id==that.choosedCourseList[j].id){
                that.$refs.multipleTable.toggleRowSelection(that.tableList[i],true)
              }
            }
          }
        })
      })
    },
    expandChangeType(e,data) {
      console.log(data)
      this.searchTypeId = e[e.length-1]
    },
    changeType(e) {
      console.log(e)
    },
    getChildArea(node, resolve) {
      let childProjects = []
      getTypeListById(node.value).then((res) => {
        childProjects = res.data
        if (node.level > 1) { // level从0开始，统一设置第3层为叶子节点，再没有下一层了
          for (const item of childProjects) {
            item.leaf = true
          }
        }
        resolve(childProjects)// 获取数据后调用resolve将子项数据渲染至视图
        console.log(this.options)
      })
    },
    getTypeList() {
      gettypeListApi({
        pageNum: 1,
        pageSize: 1000,
      }).then((res) => {
        this.options = res.data.result
      })
    },
    handleChange(value) {
      console.log(value);
    },
    handleSizeChange(val) {
      this.pageObj.pageSize = val
      this.getCourseList()
    },
    handleCurrentChange(val) {
      this.pageObj.pageNum = val
      this.getCourseList()
    },
    openCourse() {
      this.modalVisible = true
      this.getCourseList()
    },
    chooseone(row){
      this.radio = row.id
    },
    handleRemove(file, fileList) {
      this.imgFilesList = []
      this.uploadUrl = ''
      this.uploadImgId = ''
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSuccess(e) {
      if(e.code == 200) {
        this.uploadStatus = true
        this.uploadUrl = e.data.url
        this.uploadImgId = e.data.id
        this.imgFilesList = [
          {
            url: e.data.url,
            id: e.data.id,
          }
        ]
      }
    },
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.form.fee < 0) {
            this.$message.error('费用不能小于0！');
            return false;
          }
          if(this.uploadImgId === '') {
            this.$message.error('请上传专栏海报！');
          } else {
            saveApi({
              id: this.form.id,
              name: this.form.name,
              des: this.form.des,
              fee: this.form.fee?this.form.fee:0,
              picId: this.uploadImgId,
              courseTypeId: this.form.classify.length?this.form.classify[this.form.classify.length - 1]:'',
              // lessonIds: this.choosedCourseList.toString(),
              exercisePaperId: this.form.testId,
              workPaperId: this.form.taskId,
              examPaperId: this.form.examId,
              enrollStartTime: this.form.baoTime[0],
              enrollEndTime: this.form.baoTime[1],
              lessonList: this.choosedCourseList.map((item) => {return {lessonId:item.id,sort:item.sort}})
            }).then((res) => {
              this.$message.success('操作成功！');
              setTimeout(() => {
                this.$router.back(-1)
              }, 1000);
            })
          }
        } else {
          return false;
        }
      });
    },
    onCancel() {
      this.$router.back(-1)
    }
  }
}
</script>
<style>
  .hiddenUpload .el-upload--picture-card{
    display:none !important;
  }
</style>
<style scoped>
.line {
  text-align: center;
}
</style>
